<template>
    <Grid :border="border" :transferStyle="true" :column="column" :gap="gap" :template="templateData" v-bind="$attrs" />
</template>

<script setup>
import { computed, provide } from 'vue'
import Grid from '../grid/grid.vue'
import DataItem from '../data-item/data-item.vue'

const props = defineProps({
    class: String,
    style: [Object, Array],
    access: [String, Object],
    name: String,
    column: Number,
    columns: {
        type: Array,
        required: true
    },
    data: {
        type: Object,
        default: () => ({})
    },
    gap: [Number, String],
    border: Boolean,
    eventData: Object,
    eventMap: Object,
    colProps: Object
})

function useColumns(columns, config) {
    const processedColumns = computed(() => {
        return columns.value.map(col => ({
            ...col,
            // 添加默认配置
            hidden: col.hidden || false,
            // 处理排序规则
            sorter: col.sorter ? createSorter(col) : null
        }))
    })

    return {
        data: processedColumns
    }
}

function createSorter(col) {
    return (a, b) => {
        const valA = getNestedValue(a, col.dataIndex)
        const valB = getNestedValue(b, col.dataIndex)
        return typeof col.sorter === 'function'
            ? col.sorter(valA, valB)
            : defaultSorter(valA, valB)
    }
}

// 列配置处理
const profileColumns = useColumns(
    computed(() => props.columns),
    {
        enable: {
            cover: true,
            render: true,
            sort: true,
            copy: true,
            tip: true,
            popover: true
        },
        access: Object.assign(
            { handler: 'baseList' },
            typeof props.access === 'string'
                ? { name: props.access }
                : props.access
        ),
        name: props.name || 'profile',
        handler: 'baseList',
        eventData: props.eventData || {},
        eventMap: props.eventMap || {}
    }
)

// 上下文提供
provide('DetailContext', {
})

const templateData = computed(() => {
    return profileColumns.data.value.map((item, index) => {
        const key = item.key || item.name || item.dataIndex
        const value = getNestedValue(props.data, item.dataIndex)

        return {
            ...item,
            key,
            element: {
                component: DataItem,
                props: {
                    label: item.title,
                    ...item.colProps
                },
                // 处理渲染内容
                children: item.render
                    ? item.render(value, props.data, index)
                    : value
            }
        }
    })
})

const getNestedValue = (obj, path) => {
    return path.split('.').reduce((acc, key) => {
        return acc?.[key] ?? ''
    }, obj)
}
</script>



<style scoped>
.detail-container {
    box-sizing: border-box;
}
</style>